package com.aerotechnic.dao.implementation;

import java.util.List;
import java.util.StringTokenizer;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.aerotechnic.dao.implementation.GenericDao;
import com.aerotechnic.entities.BaseEntity;


public abstract class BaseDao<E extends BaseEntity> implements GenericDao<E> {
	private Class<E> type;
	private String currentGeniricClassName;

	@Autowired
	private  SessionFactory sessionFactory;
	
	public Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	public BaseDao() {
		Type t = getClass().getGenericSuperclass();
		ParameterizedType pt = (ParameterizedType) t;
		type = (Class<E>) pt.getActualTypeArguments()[0];
		currentGeniricClassName = getClassNameFromPackage();
	}

	
//	@Transactional
	public void save(E e) {
		getCurrentSession().save(e);
	}

	public void delete(int id) {
		E e = findByID(id);
		if (e != null)
			getCurrentSession().delete(e);
	}

	public E findByID(int id) {

		Session session = sessionFactory.getCurrentSession();

		return  (E) session.createQuery("FROM "+currentGeniricClassName+" where id= "+id).list().get(0);


	}

	public List<E> findAll() {
		 return getCurrentSession().createQuery("from "+currentGeniricClassName).list();
	}

	public void update(E e) {
		getCurrentSession().update(e);
	}

	private String getClassNameFromPackage() {
		StringTokenizer strTkn = new StringTokenizer(type.toString(), ".");
		String temp = "";
		while (strTkn.hasMoreElements()) {
			temp = (String) strTkn.nextElement();
		}
		return temp;
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

}
